package com.ydl.iec.transport;

import com.ydl.iec.iec104.common.BasicInstruction104;
import com.ydl.iec.iec104.core.CachedThreadPool;
import com.ydl.iec.iec104.enums.TypeIdentifierEnum;
import com.ydl.iec.iec104.message.MessageDetail;
import com.ydl.iec.iec104.server.handler.ChannelHandler;
import com.ydl.iec.iec104.server.handler.DataHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MasterHandler implements DataHandler {
    @Override
    public void handlerAdded(ChannelHandler ctx) throws Exception {
        log.info("why...");
        Runnable runnable = () -> {
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("handler Added.");
            ctx.writeAndFlush(BasicInstruction104.getGeneralCallRuleDetail104());
        };
        CachedThreadPool.getCachedThreadPool().execute(runnable);
    }

    @Override
    public void channelRead(ChannelHandler ctx, MessageDetail ruleDetail104) throws Exception {
        TypeIdentifierEnum typeIdentifier = ruleDetail104.getTypeIdentifier();
        switch (typeIdentifier){
            case generalCall:
                short cos = ruleDetail104.getTransferReason();
                if(cos == 0x0A){
                    ctx.writeAndFlush(BasicInstruction104.getDirectoryCall());
                }
                break;
            default:
        }
        log.info("主站收到数据: {}",ruleDetail104.getHexString());
    }
}
